<template>
    <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible"
      :close-on-click-modal="false" draggable>
      <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
       <el-row :gutter="24">
    <el-col :span="24" class="mb20">
      <el-form-item label="账户" prop="accountId">
        <el-select v-model="form.accountId" placeholder="请选择账户类型" style="width: 240px">
          <el-option-group
              v-for="group in state.accountsOptions"
              :key="group.label"
              :label="group.label"
          >
            <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-option-group>
        </el-select>
      </el-form-item>
      </el-col>



    <el-col :span="24" class="mb20">
      <el-form-item label="交易类型" prop="transactionType">
        <el-select collapse-tags collapse-tags-tooltip v-model="form.transactionType" @change="handleTransactionTypeChange">
          <el-option :key="index" :label="item.label" :value="item.value"
                     v-for="(item, index) in transaction_type"></el-option>
        </el-select>
      </el-form-item>
      </el-col>

    <el-col :span="24" class="mb20">
      <el-form-item label="账单分类" prop="categoryId">
        <el-select
            v-model="form.categoryId"
            placeholder="请选择分类"
            style="width: 360px"
        >
          <el-option
              v-for="item in state.categoriesOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      </el-col>

         <el-col :span="24" class="mb20">
           <el-form-item label="金额" prop="amount">
             <el-input-number :step="0.01" v-model="form.amount" placeholder="请输入金额"/>
           </el-form-item>
         </el-col>

    <el-col :span="24" class="mb20">
      <el-form-item label="交易日期" prop="date">
        <el-input v-model="form.date" placeholder="请输入交易日期"/>
        <el-date-picker type="datetime" placeholder="请输入交易日期" v-model="form.date"></el-date-picker>
      </el-form-item>
      </el-col>

    <el-col :span="24" class="mb20">
      <el-form-item label="账单描述" prop="description">
        <el-input v-model="form.description" placeholder="请输入账单描述"/>
      </el-form-item>
      </el-col>

			</el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
        </span>
      </template>
    </el-dialog>
</template>

<script setup lang="ts" name="AccTransactionsDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj, validateExist } from '/@/api/account/accTransactions'
import { rule } from '/@/utils/validate';
import {getUserAccounts} from "/@/api/account/accAccounts";
import {fetchUserByType} from "/@/api/account/accCategories";
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典
const { transaction_type } = useDict('transaction_type')

// 提交表单数据
const form = reactive({
		id:'',
	  accountId: '',
	  amount: 0,
	  transactionType: '',
	  categoryId: '',
	  date: '',
	  description: '',
});

// 定义变量内容
const state = reactive({
  accountsOptions: [] as any,
  categoriesOptions: [] as any,
})

// 定义校验规则
const dataRules = ref({
    accountId: [{required: true, message: '账户ID不能为空', trigger: 'blur'}],
    amount: [{required: true, message: '金额不能为空', trigger: 'blur'}, { validator: rule.number, trigger: 'blur' }],
    transactionType: [{required: true, message: '交易类型:1收入;2支出;3转账不能为空', trigger: 'blur'}],
    categoryId: [{required: true, message: '分类ID不能为空', trigger: 'blur'}],
    date: [{required: true, message: '交易日期不能为空', trigger: 'blur'}],
})

// 打开弹窗
const openDialog = async (id: string) => {
  visible.value = true
  form.id = ''

  // 重置表单数据
	await nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取accTransactions信息
  if (id) {
    form.id = id
    getAccTransactionsData(id)
  }

  // 查询登录用户的账户信息
  const {data: accounts} = await getUserAccounts()
  console.log('用户账单账户信息', accounts)
	state.accountsOptions = []
  const accountTypeSet = new Set<String>(accounts.map((item: any) => item.accountTypeName))
  for (const typeName of accountTypeSet) {

    const options = accounts.filter((item: any) => item.accountTypeName === typeName).map((item: any) => {
      return {
        value: item.id,
        label: item.accountName,
      }
    })
    state.accountsOptions.push({
      label: typeName,
      options,
    })
  }
	
	state.accountsOptions.push({
		label: '默认',
		options: [
			{
				value: -1,
				label: '不选择账户',
			}
		],
	})

  // 查询用户分类数据

};

// 选择交易类型
const handleTransactionTypeChange = (val: string) => {
  form.transactionType = val
  // 根据交易类型，查询分类数据
  // 查询用户分类数据
  const params = {
    categoryType: val
  }
  fetchUserByType(params).then((res: any) => {
    console.log('用户分类数据', res.data)
    state.categoriesOptions = []
    state.categoriesOptions = res.data.map((item: any) => {
      return {
        value: item.id,
        label: item.name,
        icon: item.icon
      }
    })

  })
}

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
    loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '账单记录成功!');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getAccTransactionsData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj({id: id}).then((res: any) => {
    Object.assign(form, res.data[0])
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>
